package org.tloss.web.editor.message.editors;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.layout.TreeColumnLayout;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.ICellEditorValidator;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.part.EditorPart;
import org.tloss.web.editor.Utils;
import org.tloss.web.editor.model.Field;
import org.tloss.web.editor.model.Message;

public class MessageMainEditor extends EditorPart implements
		IResourceChangeListener {
	private boolean dirty = false;
	private MessageModel message = new MessageModel();
	TreeViewer treeViewer;

	@Override
	public void doSave(IProgressMonitor monitor) {
		IEditorInput editorInput = this.getEditorInput();
		IFileEditorInput fileEditorInput = (IFileEditorInput) editorInput;
		IFile file = fileEditorInput.getFile();
		JAXBContext context;
		try {
			context = JAXBContext.newInstance(Message.class);
			Marshaller marshaller = context.createMarshaller();
			ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
			marshaller.marshal(message.getMessage(), arrayOutputStream);

			file.setContents(
					new ByteArrayInputStream(arrayOutputStream.toByteArray()),
					false, true, monitor);
			this.dirty = false;
			this.firePropertyChange(IEditorPart.PROP_DIRTY);
		} catch (JAXBException e) {
			Utils.logError("Can't save message", e);
		} catch (CoreException e) {
			Utils.logError("Can't save message", e);

		}
	}

	@Override
	public void doSaveAs() {

	}

	@Override
	public void init(IEditorSite site, IEditorInput input)
			throws PartInitException {
		if (!(input instanceof IFileEditorInput)) {
			throw new PartInitException("Input must be a file");
		}
		setSite(site);
		setInput(input);
		IFileEditorInput editorInput = (IFileEditorInput) input;
		IFile file = editorInput.getFile();
		JAXBContext context;
		InputStream inputStream =null;
		try {
			inputStream = file.getContents();
			if (inputStream.available() == 0) {
				Message msg = new Message();
				msg.setFields(new ArrayList<Field>());

				message.setMessage(msg);
			} else {
				context = JAXBContext.newInstance(Message.class);
				Unmarshaller marshaller = context.createUnmarshaller();
				Message msg = (Message) marshaller.unmarshal(inputStream);
				message.setMessage(msg);
			}
		} catch (CoreException e) {
			throw new PartInitException("Can't load resource", e);
		} catch (JAXBException e) {
			throw new PartInitException("Can't load resource", e);
		} catch (IOException e) {
			throw new PartInitException("Can't load resource", e);
		}finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public boolean isDirty() {

		return dirty;
	}

	@Override
	public boolean isSaveAsAllowed() {
		return false;
	}

	@Override
	public void createPartControl(final Composite parent) {
		Composite composite = new Composite(parent, SWT.NONE);
		GridLayout layout = new GridLayout();
		composite.setLayout(layout);
		layout.numColumns = 2;

		Composite treeContainer = new Composite(composite, SWT.BORDER);
		GridData gridData = new GridData();
		treeContainer.setLayoutData(gridData);
		gridData.horizontalAlignment = SWT.FILL;
		gridData.grabExcessHorizontalSpace = true;
		gridData.verticalAlignment = SWT.FILL;
		gridData.grabExcessVerticalSpace = true;
		TreeColumnLayout treeLayout = new TreeColumnLayout();
		treeContainer.setLayout(treeLayout);
		treeViewer = new TreeViewer(treeContainer, SWT.MULTI
				| SWT.FULL_SELECTION);
		Tree tree = treeViewer.getTree();
		tree.setHeaderVisible(true);
		TreeColumn keyColumn;

		keyColumn = new TreeColumn(tree, SWT.NONE);
		keyColumn.setText("Name");
		treeLayout.setColumnData(keyColumn, new ColumnWeightData(2));

		treeViewer.setContentProvider(new WorkbenchContentProvider());
		final WorkbenchLabelProvider treeLabelProvider = new WorkbenchLabelProvider();
		treeViewer.setLabelProvider(treeLabelProvider);

		TreeViewerColumn column1 = new TreeViewerColumn(treeViewer, keyColumn);

		column1.setLabelProvider(new ColumnLabelProvider() {
			public String getText(Object element) {
				return treeLabelProvider.getText(element);
			}

			public Image getImage(Object element) {

				return treeLabelProvider.getImage(element);
			}
		});

		column1.setEditingSupport(new EditingSupport(treeViewer) {
			TextCellEditor editor = null;

			protected boolean canEdit(Object element) {
				return true;
			}

			protected CellEditor getCellEditor(Object element) {
				if (editor == null) {
					Composite tree = (Composite) treeViewer.getControl();
					editor = new TextCellEditor(tree);
					editor.setValidator(new ICellEditorValidator() {
						public String isValid(Object value) {
							if (value == null
									|| ((String) value).trim().length() == 0)
								return "Key must not be empty string";
							Message msg = message.getMessage();
							List<Field> fields = msg.getFields();
							if (fields != null && fields.size() > 0) {
								for (int i = 0; i < fields.size(); i++) {
									if (value.equals(fields.get(i).getName())) {
										return "Name must be unique";
									}
								}
							}
							return null;
						}
					});

				}
				return editor;
			}

			protected Object getValue(Object element) {
				return treeLabelProvider.getText(element);
			}

			protected void setValue(Object element, Object value) {
				if (value != null) {
					String text = ((String) value).trim();
					if (element instanceof FieldElement) {
						Field field = ((FieldElement) element).getField();
						if (field.getName() != null || text != null) {
							if ((text != null && !text.equals(field.getName()))
									|| (field.getName() != null && !field
											.getName().equals(text))) {

								field.setName(text);
								treeModified(element);
							}
						}
					}
				}
			}
		});
		getSite().setSelectionProvider(treeViewer);

		treeViewer.setInput(new MessageElement(message, this));

		treeViewer.setAutoExpandLevel(TreeViewer.ALL_LEVELS);

		Composite wrapper = new Composite(composite, SWT.NONE);
		RowLayout rowLayout = new RowLayout();
		wrapper.setLayout(rowLayout);
		rowLayout.type = SWT.VERTICAL;

		Button button = new Button(wrapper, SWT.NONE);
		button.setText("Add");
		Button buttonDelete = new Button(wrapper, SWT.NONE);
		buttonDelete.setText("Delete");

		buttonDelete.addMouseListener(new MouseListener() {

			@Override
			public void mouseUp(MouseEvent e) {

			}

			@Override
			public void mouseDown(MouseEvent e) {
				TreeItem[] items = treeViewer.getTree().getSelection();
				Message msg = message.getMessage();
				for (int i = 0; i < items.length; i++) {
					msg.getFields().remove(
							((FieldElement) items[i].getData()).getField());
				}
				treeModified(null);

			}

			@Override
			public void mouseDoubleClick(MouseEvent e) {

			}
		});

		button.addMouseListener(new MouseListener() {

			@Override
			public void mouseUp(MouseEvent e) {

			}

			@Override
			public void mouseDown(MouseEvent e) {
				Field field = new Field();
				field.setName("field" + System.currentTimeMillis());
				field.setType("java.lang.Object");
				Message msg = message.getMessage();
				if (msg == null) {
					msg = new Message();
					message.setMessage(msg);
				}
				List<Field> fields = msg.getFields();
				if (fields == null) {
					fields = new ArrayList<Field>();
					msg.setFields(fields);
				}
				fields.add(field);
				treeModified(null);

			}

			@Override
			public void mouseDoubleClick(MouseEvent e) {

			}
		});
	}

	@Override
	public void setFocus() {

	}

	public void treeModified(Object element) {
		if (element == null)
			treeViewer.refresh();
		else
			treeViewer.refresh(element);
		dirty = true;
		firePropertyChange(IEditorPart.PROP_DIRTY);

	}

	@Override
	public void resourceChanged(IResourceChangeEvent event) {
		treeModified(null);
	}
}
